# -*- coding: utf-8 -*-

#
# Copyright (c) 2012-2023 Virtual Cable S.L.U.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
#    * Redistributions of source code must retain the above copyright notice,
#      this list of conditions and the following disclaimer.
#    * Redistributions in binary form must reproduce the above copyright notice,
#      this list of conditions and the following disclaimer in the documentation
#      and/or other materials provided with the distribution.
#    * Neither the name of Virtual Cable S.L.U. nor the names of its contributors
#      may be used to endorse or promote products derived from this software
#      without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""
Author: Adolfo Gómez, dkmaster at dkmon dot com
"""
import logging
import typing

from django.db import models

from uds.core.types.states import State
from uds.core.environment import Environment
from uds.core import jobs, consts


logger = logging.getLogger(__name__)


class Scheduler(models.Model):
    """
    Class that contains scheduled tasks.

    The scheduled task are keep at database so:
    * We can access them from any host
    * We have a persistence for them

    The Scheduler contains jobs, that are clases that manages the job.
    Jobs are not serialized/deserialized, they are just Task delegated to certain clases.

    In order for a task to work, it must first register itself for "names" that that class handles using the
    JobsFactory
    """

    DAY = 60 * 60 * 24
    HOUR = 60 * 60
    MIN = 60

    name = models.CharField(max_length=64, unique=True)
    frecuency = models.PositiveIntegerField(default=DAY)
    last_execution = models.DateTimeField(db_index=True)
    next_execution = models.DateTimeField(default=consts.NEVER, db_index=True)
    owner_server = models.CharField(max_length=consts.system.MAX_DNS_NAME_LENGTH, db_index=True, default='')
    state = models.CharField(max_length=1, default=State.FOR_EXECUTE, db_index=True)

    # primary key id declaration (for type checking)

    # "fake" declarations for type checking
    # objects: 'models.manager.Manager[Scheduler]'
    id: int  # Primary key (Autogenerated by model, just for type checking)

    class Meta():  # pyright: ignore
        """
        Meta class to declare default order and unique multiple field index
        """

        app_label = 'uds'

    def get_environment(self) -> Environment:
        """
        Returns an environment valid for the record this object represents
        """
        return Environment.environment_for_table_record(self._meta.verbose_name or self._meta.db_table, self.id)

    def get_instance(self) -> typing.Optional[jobs.Job]:
        """
        Returns an instance of the class that this record of the Scheduler represents. This clas is derived
        of uds.core.jobs.Job.Job
        """
        job_instance_type = jobs.factory().lookup(self.name)

        if job_instance_type:
            return job_instance_type(self.get_environment())

        return None

    @staticmethod
    def pre_delete(sender: typing.Any, **kwargs: typing.Any) -> None:  # pylint: disable=unused-argument
        """
        Used to remove environment for sheduled task
        """
        to_delete: 'Scheduler' = kwargs['instance']
        logger.debug('Deleting sheduled task %s', to_delete)
        to_delete.get_environment().clean_related_data()

    def __str__(self) -> str:
        return f'Scheduled task {self.name}, every {self.frecuency}, last execution at {self.last_execution}, state = {self.state}'


# Connects a pre deletion signal to Scheduler
models.signals.pre_delete.connect(Scheduler.pre_delete, sender=Scheduler)
